<script>
import { Search, ArrowRight, ArrowLeft } from "@element-plus/icons-vue";
import { StudioAPI } from "../apis";
import { ElMessage } from "element-plus";
import DraggableUpload from "../components/DraggableUpload.vue";

import { ref } from "vue";
export default {
  setup() {
    const mediaRef = ref(null);
    return {
      mediaRef,
    };
  },

  data() {
    return {
      uploadFun: StudioAPI.draggableUpload,
      query: {
        page: 1,
        scene: null,
        keywords: null,
        page_size: 20,
      },
      promos: [],
      has_more: false,
      scenes: ["BANNER", "NOTIFICATION"],
      editing_promo: {
        promo_id: null,
        title: "",
        media_url: null,
        scene: "BANNER",
        mp_path: "",
        priority: 1,
      },
    };
  },
  components: {
    DraggableUpload,
    Search,
    ArrowRight,
    ArrowLeft,
  },
  async mounted() {
    await this.switchScene(this.scenes[0]);
  },
  methods: {
    async getPromos() {
      const promos = await StudioAPI.getPromos(this.query);
      this.promos = promos;
      this.has_more = promos.length === this.query.page_size;
    },
    async switchScene(scene) {
      this.query.scene = scene;
      this.query.page = 1;
      await this.getPromos();
    },
    async nextPage() {
      this.query.page += 1;
      await this.getPromos();
    },
    async prevPage() {
      this.query.page -= 1;
      await this.getPromos();
    },
    async searchPromos() {
      this.query.page = 1;
      await this.getPromos(this.query);
    },
    async confirmKeywords(page) {
      this.query.page = isNaN(page) ? 1 : page;
      await this.getPromos();
    },

    // 点击顾客行
    async clickPromoRow(promo) {
      const index = this.promos.findIndex((c) => c.promo_id === promo.promo_id);
      if (index < 0) return;
      this.editing_promo = Object.assign({}, promo);

      this.mediaRef.images = [{ url: this.editing_promo.media_url }];
    },

    async addPromo() {
      this.reset();
    },

    async confirmUpsert() {
      this.editing_promo.media_url = this.mediaRef.images.map(
        (i) => i.response || i.url
      )[0];

      if (this.editing_promo.promo_id) {
        const {
          success,
          data: promo,
          message,
        } = await StudioAPI.updatePromo({
          ...this.editing_promo,
        });
        if (!success) {
          ElMessage.warning(message);
          return;
        }

        // 出错
        if (!promo.promo_id) throw promo;

        const index = this.promos.findIndex(
          (p) => p.promo_id === promo.promo_id
        );
        if (index > -1) {
          this.promos[index] = promo;
        }
      } else {
        const {
          success,
          data: promo,
          message,
        } = await StudioAPI.createPromo({
          ...this.editing_promo,
        });
        if (!success) {
          ElMessage.warning(message);
          return;
        }

        // 出错
        if (!promo.promo_id) throw promo;
        this.promos.splice(0, 0, promo);
      }
      this.reset();
    },
    reset() {
      this.editing_promo = {
        promo_id: null,
        name: "",
        price: 100,
        original_price: 0,
        media_url: null,
        remark: "",
        priority: 0,
      };
    },
  },
};
</script>
<template>
  <el-container>
    <el-main style="padding: 5px" width="auto">
      <div class="filter-header">
        <!-- 底部换页 -->
        <div style="display: flex; overflow: scroll">
          <div style="margin-right: 10px" v-for="scene of scenes" :key="scene">
            <el-button
              :type="scene === query.scene ? 'primary' : 'default'"
              @click="switchScene(scene)"
              >{{ scene }}</el-button
            >
          </div>
        </div>
      </div>

      <div class="filter-header">
        <!-- 底部换页 -->
        <div style="display: flex">
          <el-input
            v-model="query.keywords"
            clearable
            placeholder="名字"
            size="large"
            @keyup.enter="confirmKeywords"
          >
            <template #prefix>
              <el-icon class="el-input__icon"><search /></el-icon>
            </template>
          </el-input>
          <div style="flex: 1; margin-left: 20px">
            <el-button
              @click="prevPage"
              :disabled="query.page === 1"
              size="large"
              style="width: 100%"
            >
              <el-icon size="20"><arrow-left /></el-icon>
            </el-button>
          </div>
          <div style="flex: 1; margin-left: 5px">
            <el-button
              @click="nextPage"
              :disabled="!has_more"
              size="large"
              style="width: 100%"
            >
              <el-icon size="20"><arrow-right /></el-icon>
            </el-button>
          </div>
        </div>
        <div>
          <el-button @click="addPromo" size="large" style="width: 100%">
            添加销售
          </el-button>
        </div>
      </div>
      <el-table
        :data="promos"
        highlight-current-row
        height="88vh"
        @row-click="clickPromoRow"
        stripe
      >
        <el-table-column label="图片" width="100">
          <template #default="scope">
            <el-image
              style="width: 40px; height: 40px"
              :src="scope.row.media_url"
              fit="cover"
              :preview-src-list="[scope.row.media_url]"
              :preview-teleported="true"
            />
          </template>
        </el-table-column>

        <el-table-column label="类别" width="160">
          <template #default="scope">
            <el-tag size="large" disable-transitions>{{
              scope.row.scene
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="名字" width="140" />
        <el-table-column prop="scene" label="场景" width="140" />
        <el-table-column prop="priority" label="优先级" width="140" />
        <el-table-column prop="mp_path" label="小程序" />
      </el-table>
    </el-main>
    <!-- 右侧表单 -->
    <el-aside style="padding: 5px; width: 400px">
      <el-card shadow="hover">
        <template #header>
          <div class="flex-between">
            <div style="font-size: var(--el-font-size-large)">增改销售</div>
            <div>
              <el-button type="primary" @click="confirmUpsert" size="large">
                保存
              </el-button>
            </div>
          </div>
        </template>
        <el-form :model="editing_promo" label-width="80px">
          <el-form-item label="场景" prop="scene">
            <el-radio-group
              v-model="editing_promo.scene"
              :disabled="editing_promo.promo_id !== null"
            >
              <el-radio
                v-for="scene in scenes"
                :key="scene"
                :label="scene"
                size="large"
                border
              >
                {{ scene }}
              </el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="名字" prop="name">
            <el-input v-model="editing_promo.title" />
          </el-form-item>

          <el-form-item label="小程序" prop="mp_path">
            <el-input v-model="editing_promo.mp_path" />
          </el-form-item>

          <el-form-item label="优先级" prop="priority">
            <el-input-number v-model="editing_promo.priority" />
          </el-form-item>

          <el-form-item label="预览图" prop="media_url">
            <draggable-upload
              ref="mediaRef"
              :upload-fun="uploadFun"
              :multiple="false"
            ></draggable-upload>
          </el-form-item>
        </el-form>
      </el-card>
    </el-aside>
  </el-container>
</template>

<style scoped>
.image-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, 200px);
  row-gap: 10px;
  column-gap: 10px;
  grid-auto-rows: 240px;
  overflow: auto;
  height: calc(100vh - 70px);
}

.image-item {
  position: relative;
  width: 200px;
  height: 200px;
  border-radius: 5px;
}

.el-table .el-table__cell {
  position: unset;
}
</style>
